<?php

/***  Documentation

    Simpletest Template
    
    Revision: $Rev$
    Last Update: $Date: 2009-09-27 21:58:34 +0000 (Sun, 27 Sep 2009) $
    Author: Tom at klenwell@gmail.com
  
NOTES

______________________________________________________________________________*/

#error_reporting(E_ALL);
$dn1 = dirname;
$ds = DIRECTORY_SEPARATOR;
$libdir = $dn1($dn1($dn1(__FILE__))) . $ds . 'lib' . $ds;
$grqdir = $dn1($libdir) . $ds . 'greqo' . $ds;
require_once($libdir . "simpletest{$ds}unit_tester.php");
require_once($grqdir . "greqo.class.php");

class GreqoClassTestCase extends UnitTestCase {
    
    var $debug = 0;
    var $is_set_up_once = 0;
    
    function setUp() 
    {
        $this->setUpOnce();    
    }
    
    function tearDown() 
    {
    }
    
    function setUpOnce()
    {
        if ( $this->is_set_up_once ) return;      
        
        // set up
        $utime = microtime();
        $this->start_timer = substr($utime,0,9) + substr($utime,-10);
        $this->is_set_up_once = 1;
        
        // Greqo class
        $this->Greqo = new Greqo($start_session=0);        
    }
    
    

    /* TEST METHODS */  
    function testInstance()
    {        
        $this->assertTrue(is_a($this->Greqo, 'Greqo'));
    }
    
    function testInit()
    {
        $this->assertTrue(is_dir($this->Greqo->cache_dir));
    }
    
    function testLog()
    {
        $m = 'testLog (unit test)';
        $this->Greqo->log($m);
        $this->assertTrue(array_search($m, $this->Greqo->Log_));
    }
    
    function testDebugLog()
    {
        $d = $this->Greqo->debug_;
        $this->Greqo->debug_ = GREQO_DEBUG_LOG;
        $this->Greqo->debug('testDebugLog (unit test)');
        $this->Greqo->debug_ = $d;
    }
    
    function testDebugPrint()
    {
        $d = $this->Greqo->debug_;
        $this->Greqo->debug_ = GREQO_DEBUG_PRINT;
        $this->Greqo->debug('testDebugPrint (unit test)');
        $this->Greqo->debug_ = $d;
    }
    
        
    function testDebugTriggerError()
    {
        $d = $this->Greqo->debug_;
        $this->Greqo->debug_ = GREQO_DEBUG_LOG;
        $this->expectError();
        $this->Greqo->trigger_error('testDebugTriggerError (unit test)');
        $this->Greqo->debug_ = $d;
    }
    
    function testDebugTriggerRequestError()
    {
        $d = $this->Greqo->debug_;
        $this->Greqo->debug_ = GREQO_DEBUG_LOG;
        $this->expectError();
        $this->Greqo->_trigger_request_error('testDebugTriggerRequestError (unit test)');
        $this->Greqo->debug_ = $d;
    }
    
    function testGetUrl()
    {
        $url = 'http://www.klenwell.com/';
        $this->assertTrue($this->Greqo->get_url($url));
        #$this->pr($this->Greqo->GreqoResponse);
    }
    
    function testUrlGet()
    {
        $url = 'http://code.google.com/p/greqo/';
        $expect = '<a href="http://www.gnu.org/licenses/old-licenses/gpl-2.0.html" rel="nofollow">GNU General Public License v2</a>';
        $content = $this->Greqo->get($url);
        $this->assertPattern(sprintf('^%s^i', $expect), $content);
        $this->assertNotNull($this->Greqo->GreqoResponse->HEADERS['date']);
        #$this->pr($this->Greqo->GreqoResponse);
    }
    
    function testUrlPost()
    {
        $url = 'http://php.net/search.php';
        $expect = '<h1 class="refname">explode</h1>';
        $PostData = array(
            'pattern' => 'explode',
            'show' => 'quickref',
            'x' => '6', 'y' => '6'
        );
        $this->Greqo->allowed_redirects = 5;
        $content = $this->Greqo->post($url, $PostData);
        $this->assertPattern(sprintf('^%s^i', $expect), $content);
        $this->assertNotNull($this->Greqo->GreqoResponse->HEADERS['date']);
        #$this->pr($this->Greqo->GreqoResponse);
    }
    
    function testGetDatestamp()
    {
        $time = time();
        $ds = $this->Greqo->get_datestamp($time);
        $timeback = strtotime(str_replace(array('T','Z'), array(' ', ''), $ds));
        $this->assertEqual($time, $timeback);
    }
    
    function testRfc3339()
    {
        $date = '2008-01-01 12:00:00';
        $uts = strtotime($date);
        $expect = '2008-01-01T12:00:00Z';
        
        $this->assertEqual($this->Greqo->rfc3339($date), $expect);
        $this->assertEqual($this->Greqo->rfc3339($uts), $expect);
        $this->assertEqual($this->Greqo->rfc3339($expect), $expect);
        
        $this->expectError();
        $this->Greqo->rfc3339('invalid input');
    }
    
    function testAbsoluteUrl()
    {
        $expect = 'https://www.google.com/accounts/TokenAuth';
        $this->assertEqual( $expect,
            $this->Greqo->absolute_url('https://www.google.com/', 'accounts/TokenAuth') );
        $this->assertEqual( $expect,
            $this->Greqo->absolute_url('https://www.google.com', '/accounts/TokenAuth') );
        $this->assertEqual( $expect,
            $this->Greqo->absolute_url('https://www.google.com/', '/accounts/TokenAuth') );
        $this->assertEqual( $expect,
            $this->Greqo->absolute_url('https://www.google.com', 'accounts/TokenAuth') );
    }
    
    function testSetAuthToken()
    {
        $token = md5('unit test');
        $this->Greqo->_set_auth_token($token);
        $this->assertEqual($_SESSION['GDATA']['auth_token'], $token);
        $this->assertEqual($this->Greqo->gdata_auth_token, $token);
    }
    
    function testPreloadLogin()
    {
        $this->Greqo->login_file = $this->Greqo->conf_dir . 'login.php-dist';
        $this->assertTrue($this->Greqo->_preload_login());
        $this->assertEqual($this->Greqo->email, 'YOUR_USER_NAME@gmail.com');
        $this->assertEqual($this->Greqo->password, 'YOUR_PASSWORD');
        
        # this has been removed from login config for now
        #$this->assertEqual($this->Greqo->LoginData['BloggerList']['your_blog_id'],
        #    '0000000000000000000');
    }
    
    function testGreqoClient()
    {
        $this->assertTrue(is_a($this->Greqo->GreqoClient, 'HTTP_Request'));   
    }
    
    function testResetGreqoClient()
    {
        $url = 'http://google.com/';
        $this->Greqo->GreqoClient->setURL($url);
        $this->assertEqual($this->Greqo->GreqoClient->_url->url, $url);
        
        // test load (no reset)
        $this->Greqo->load_http_client();
        $this->assertEqual($this->Greqo->GreqoClient->_url->url, $url);
        
        // test reset
        $this->Greqo->reset_http_client();
        $this->assertFalse($this->Greqo->GreqoClient->_url);
    }
    
    function testSendClientRequest()
    {
        $url = 'http://google.com/';
        $this->Greqo->GreqoClient->setURL($url);
        $this->Greqo->GreqoClient->setMethod(HTTP_REQUEST_METHOD_GET);
        $this->Greqo->_send_client_request();
        $this->assertPattern('@<title>Google</title>@', $this->Greqo->GreqoResponse->body);
        $this->assertEqual($this->Greqo->GreqoResponse->code, 200);
    }
    
    function testLoadMagpie()
    {
        $this->assertFalse(class_exists('MagpieRSS'));
        $this->Greqo->load_magpie();
        $this->assertTrue(class_exists('MagpieRSS'));
    }
    
    function testAtomToArray()
    {
        // source: http://en.wikipedia.org/wiki/Atom_(standard)#Example_of_an_Atom_1.0_Feed
        $atom_xml = <<<XML0
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 
 <title>Example Feed</title>
 <subtitle>A subtitle.</subtitle>
 <link href="http://example.org/feed/" rel="self"/>
 <link href="http://example.org/"/>
 <updated>2003-12-13T18:30:02Z</updated>
 <author>
   <name>John Doe</name>
   <email>johndoe@example.com</email>
 </author>
 <id>urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6</id>
 
 <entry>
   <title>Atom-Powered Robots Run Amok</title>
   <link href="http://example.org/2003/12/13/atom03"/>
   <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
   <updated>2003-12-13T18:30:02Z</updated>
   <summary>Some text.</summary>
 </entry>
 
</feed>
XML0;

        $AtomArray = $this->Greqo->atom_to_array($atom_xml);
        $this->assertEqual($AtomArray['CHANNEL'][0], 'Example Feed');
        $this->assertEqual($AtomArray['ITEM'][0]['title'], 'Atom-Powered Robots Run Amok');
    }
    
    function testAtomToArrayError()
    {
        $atom_xml = <<<XML0
<?html version="1.0" encoding="utf-8"?>
<feed_ xmlns="http://www.w3.org/2005/Atom">
 this is invalid xml 
</feed>
XML0;

        $this->expectError();
        $AtomArray = $this->Greqo->atom_to_array($atom_xml);
    }
    
    function testLoadCacher()
    {
        $this->assertFalse(class_exists('Cache_Lite'));
        $this->Greqo->load_cacher();
        $this->assertTrue(class_exists('Cache_Lite'));
    }
    
    function testCacheSaveAndGetAndRemove()
    {
        $id = 'unit_test';
        $data = 'They also serve who only stand and wait';
        
        // make tmp cache
        $tmp_cache = $this->Greqo->tmp_dir . 'test_cache';
        if ( mkdir($tmp_cache) ) $this->Greqo->cache_dir = $tmp_cache;        
        
        // save and get cache
        $this->Greqo->load_cacher();
        $this->assertTrue($this->Greqo->Cacher->save($data, $id));
        $cached = $this->Greqo->Cacher->get($id);
        $this->assertEqual($cached, $data);
        
        // remove and delete tmp cache
        if ( is_dir($tmp_cache) ) $this->assertTrue(rmdir($tmp_cache));
        $this->assertTrue($this->Greqo->Cacher->remove($id));
    }
    
    function testCacheClean()
    {
        $this->Greqo->load_cacher();
        $this->assertTrue($this->Greqo->clean_cache());
    }
    
    function testLoadMailer()
    {
        $this->assertFalse(class_exists('PhpMailer'));
        $this->Greqo->load_mailer();
        $this->assertTrue(class_exists('PHPMailer'));
    }
    
    function testIsAuthRequestPrepared()
    {
        $this->Greqo->email = 'test@gmail.com';
        $this->Greqo->password = '********';
        $this->Greqo->service = 'Blogger';
        $this->assertTrue($this->Greqo->_is_auth_request_prepared());
    }
    
    function testIsAuthRequestPreparedFalse()
    {
        $this->Greqo->email = '';
        $this->Greqo->password = '********';
        $this->Greqo->service = 'Blogger';
        $this->expectError();
        $this->assertFalse($this->Greqo->_is_auth_request_prepared());
    }
    
    function testIsLoginPrepared()
    {
        $this->Greqo->email = 'test@gmail.com';
        $this->Greqo->password = '********';
        $this->assertTrue($this->Greqo->_is_login_prepared());
    }
    
    function testEscapeEntities()
    {
        $in = '<>\'';
        $this->assertEqual('&lt;&gt;&apos;', $this->Greqo->escape_entities($in));
    }



    /* HELPER METHODS */
    function get_script_time()
    {
        $utime = microtime();
        return number_format((substr($utime,0,9) + substr($utime,-10)) - $this->start_timer, 4);
    }

    function kill($html, $message='dying')
    {
        $this->print_d(htmlspecialchars($html), '#600');
        print $html;
        die($message);
    }
    
    function echo_d($message, $color='#ccc')
    {
        $_D = debug_backtrace();
        $f = basename($_D[0]['file']);
        $l = $_D[0]['line'];
        $loc = "{$f}:{$l}";
        $out = "<div style='line-height:1.5em; font-family:monospace; color:$color;'>$message <span style='color:#666;'>[$loc]</span></div>";
        $this->_DBG[] = "$loc -> " . strip_tags($message);
        echo $out;
        return;
    }
    
    function print_d($message, $color='#c33')
    {
        if ( $this->debug ) $this->echo_d($message, $color);
        return;
    }
    
    function print_r($Mixed)
    {
        $return = htmlspecialchars(print_r($Mixed, 1));
        $return = "<pre>$return</pre>";
        return $return;
    }
    
    function pr($Mixed, $header='')
    {
        if ( !empty($header) ) $header = "<b>$header</b>";
        $return = htmlspecialchars(print_r($Mixed, 1));
        $return = "<pre style='border:1px solid #ccc; background:#f3f3f3; padding:4px;'>$header\n\n$return</pre>";
        $this->echo_d($return, '#333');
    }
    
    function dump()
    {
        echo $this->print_r($this);
        return;
    }
}


$Test = &new GreqoClassTestCase();
$Test->run(new HtmlReporter());

$Test->echo_d('test complete in '.$Test->get_script_time().' s', '#600');
?>
